package webdav

import (
	"fmt"
	"my189go/pkg"
	"my189go/pkg/file"
	"net/http"
	"path/filepath"
)

func (h *CloudFileSystem) handlePut(w http.ResponseWriter, r *http.Request) (status int, err error) {
	reqPath, status, err := h.stripPrefix(r.URL.Path)
	if err != nil {
		return status, err
	}
	if r.ContentLength == 0 {
		return http.StatusCreated, nil
	}
	dir, name := filepath.Split(reqPath)
	parent, err := h.app.Stat(dir)
	if err != nil {
		return http.StatusNotFound, err
	}
	f := file.NewWebFile(parent.(pkg.File).Id(), name, r)
	if copyErr := h.app.UploadFrom(f); copyErr != nil {
		return http.StatusMethodNotAllowed, copyErr
	}
	stat, err := h.app.Stat(reqPath)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	w.Header().Set("ETag", stat.Name()+stat.ModTime().String())
	return http.StatusCreated, nil
}

func (h *CloudFileSystem) handlePostUpload(w http.ResponseWriter, r *http.Request) (status int, err error) {
	formFile, m, err := r.FormFile("file")
	if err != nil {
		fmt.Printf("get formFile fail\n")
		return 0, err
	}

	dir := r.PostForm.Get("remote_dir")

	defer formFile.Close()
	name := m.Filename

	parent, err := h.app.Stat(dir)
	if err != nil {
		fmt.Printf("get %s info fail\n", dir)
		return http.StatusNotFound, err
	}
	f := file.NewWebFile2(parent.(pkg.File).Id(), name, formFile, m.Size)
	fmt.Printf("start uploading %s%s \n", dir, name)
	if copyErr := h.app.UploadFrom(f); copyErr != nil {
		fmt.Printf("upload %s/%s fail %s\n", dir, name, copyErr)
		return http.StatusMethodNotAllowed, copyErr
	}
	fmt.Printf("upload %s to %s success\n", name, dir)
	return http.StatusCreated, nil
}
